// 购物车逻辑
const onBox = document.querySelector('.on_off>.on');
const offBox = document.querySelector('.on_off>.off');
const regBox = document.querySelector('.regi');
const goodsBox = document.querySelector('.cart_goods');
const hmoneyBox = document.querySelector('.jiesuan>span:nth-child(2)');
const fmoneyBox = document.querySelector('.total_money>span');
const chedBox = document.querySelector('.ched>span');

// 1.登录检测
loginTest();
async function loginTest() {
    const id = window.localStorage.getItem('id');
    const token = window.localStorage.getItem('token');
    if(!id || !token) {
        window.localStorage.setItem('url', 'cart');
        window.location.href = './login.html';
        return;
    }
    // 发送请求，检测token的有效性
    const res = await pAjax({
        url: 'http://localhost:8888/users/info',
        data: `id=${id}`,
        dataType:'json',
        token,
    })
    console.log(res);
    if(res.code === 1) {
       offBox.classList.remove('active');
       onBox.innerText = res.info.nickname;
       onBox.classList.add('active');
       regBox.style.visibility = 'hidden';
    } else{
        window.localStorage.setItem('url', 'list');
        window.location.href = './login.html';
        return;
    }
}

// 2.全部商品滑动切换
$('.all>ul>li').mouseover(function() {
    $(this).parent().find('span').stop().animate({left:$(this).index() * 150}, 50);
    $(this).css('color', 'white').siblings().css('color', 'black');
})


//3.渲染商品信息
// 拿到本地存储的cartlist
let cartList = JSON.parse(window.localStorage.getItem('cartList')) || [];
// 判断购物车是否为空
if(!cartList.length) {
    goodsBox.innerHTML = '<h2>你的购物车空空如也哦,快去买东西吧！</h2>';
}else{
    bindHtml();
}

function bindHtml() {
    let str = '';
    cartList.forEach(item => {
        str += `
        <li class="item" data-id="${item.id}">
            <input type="checkbox" class="single" data-id="${item.id}">
            <p class="pic"><img src="${item.img_url}" alt=""></p>
            <p class="title">${item.title}</p>
            <p class="size">尺码：<span>${item.size}</span></p>
            <p class="each_price">￥${item.price}</p>
            <div class="add_sub">
                <span class="sub">-</span>
                <span class="count"><input type="text" value="${item.num}"></span>
                <span class="add">+</span>
            </div>
            <div class="total_price">
                ￥${((item.price-0) * (item.num-0)).toFixed(2)}
            </div>
            <button data-id=${item.id}>删除</button>
        </li>
        `
    })
    goodsBox.innerHTML = str;
}  

// 5.绑定点击事件
const tquanxuan = document.querySelector('.tquanxuan')
const fquanxuan = document.querySelector('.quanxuan>input');
const singleAll = document.querySelectorAll('.single')
goodsBox.addEventListener('click', e => {
    e = e || window.event;
    const target = e.target || e.srcElement;
    // 数量减
    if(target.className === 'sub') {
        let currentNum = target.nextElementSibling.firstElementChild.value - 0;
        if(currentNum > 1) currentNum --;
        target.nextElementSibling.firstElementChild.value = currentNum;
        const id = target.parentElement.parentElement.dataset.id;
        cartList.find(item => item.id === id).num = currentNum;
        window.localStorage.setItem('cartList', JSON.stringify(cartList));
        bindHtml()  
        
        
    }
    // 数量加
    if(target.className === 'add') {
        let currentNum = target.previousElementSibling.firstElementChild.value - 0;
        currentNum ++;
        target.previousElementSibling.firstElementChild.value = currentNum;
        const id = target.parentElement.parentElement.dataset.id;
        cartList.find(item => item.id === id).num = currentNum;
        window.localStorage.setItem('cartList', JSON.stringify(cartList));
        bindHtml()  
    }
    // 删除button
    if(target.tagName === 'BUTTON') {
        // 找到要删除的那条数据
        const id = target.dataset.id;
        const res = cartList.find(item => item.id === id);
        cartList.splice(cartList.indexOf(res),1);
        window.localStorage.setItem('cartList', JSON.stringify(cartList));
        bindHtml();
        window.history.go(0);
    }

    
    if(target.className === "single") {
        let money = hmoneyBox.innerText - 0;
        const data = cartList.find(item => item.id === target.dataset.id);
        if(target.checked) {
            money += (data.num - 0) * (data.price - 0);
            hmoneyBox.innerText = money.toFixed(2);
            fmoneyBox.innerText = money.toFixed(2);
        }else{
            money -= (data.num - 0) * (data.price - 0);
            hmoneyBox.innerText = money.toFixed(2);
            fmoneyBox.innerText = money.toFixed(2);
        }

        let count = 0;
        for(let j = 0; j<singleAll.length; j++) {
            if(singleAll[j].checked) count++;
        }
        fquanxuan.checked = count === singleAll.length;
        tquanxuan.checked = count ===singleAll.length;
        
    }
})

// 6.全选



fquanxuan.onclick = function() {
    let total_money = 0;
    let sum = 0;
    for(let i = 0; i<singleAll.length; i++) {
        singleAll[i].checked = fquanxuan.checked;
        //修改总金额，修改总数量
        if(this.checked) {
            const shangping = cartList.find(item => item.id === singleAll[i].dataset.id) 
            total_money += (shangping.price - 0) * (shangping.num - 0)
            fmoneyBox.innerText = total_money.toFixed(2);
            sum += shangping.num - 0;
            chedBox.innerText = sum;   
        }else{
            fmoneyBox.innerText = "0.00";
            chedBox.innerText = "0";
        }
    }
}
tquanxuan.onclick = function() {
    let total_money = 0;
    for(let i = 0; i<singleAll.length; i++) {
        singleAll[i].checked = tquanxuan.checked;
        if(this.checked) {
            const shangping = cartList.find(item => item.id === singleAll[i].dataset.id) 
            total_money += (shangping.price - 0) * (shangping.num - 0)
            hmoneyBox.innerText = total_money.toFixed(2);
        }else{
            hmoneyBox.innerText = "0.00";
        }
        
    } 
    
}










